package com.yjd.api.user;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.util.ZhimaAuthUtils;
import com.yjd.comm.zhima.model.ZhimaAuthApplyModel;
import com.yjd.comm.zhima.model.ZhimaCallBackModel;
import com.yjd.comm.zhima.model.ZhimaCreditDataModel;
import com.yjd.comm.zhima.model.ZhimaCreditModel;
import com.yjd.comm.zhima.service.IZhimaCreditService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 芝麻信用授权
 * Created by yjd-wap on 2017/8/21.
 */
@Controller
@Scope("prototype")
@RequestMapping("/zhimaAuth/")
public class ZhimaAuthControl extends BaseControl {

    @Resource
    private IZhimaCreditService zhimaCreditService;

    @RequestMapping("apply")
    public String apply() throws Exception {
        Long user_id = super.getSessionUserId();
        ZhimaCreditModel zhimaCreditModel = zhimaCreditService.authApply(user_id);
        ZhimaAuthApplyModel authApplyModel = ZhimaAuthUtils.getZhimaAuthModel(zhimaCreditModel.getUser_id(), zhimaCreditModel.getIdname(),
                zhimaCreditModel.getIdcard());
        request.setAttribute("auth_url", authApplyModel.getAuthUrl());
        request.setAttribute("app_msg", authApplyModel.getApplyData());
        return "auth/zhima";
    }

    @ResponseBody
    @RequestMapping("callback")
    public String callback(String app_msg) throws Exception {
        Long user_id = super.getSessionUserId();
        if (StringUtil.isEmpty(app_msg)) {
            FrameUtil.throwBaseException1("参数错误");
        }
        ZhimaCallBackModel callBackModel = ZhimaAuthUtils.parseZhimaCreditData(app_msg);
        ZhimaCreditDataModel creditDataModel = new ZhimaCreditDataModel();
        creditDataModel.setIndustry_level(callBackModel.getIndustry_level());
        creditDataModel.setFraud_flag(callBackModel.getFraud_flag());
        creditDataModel.setCredit_score(callBackModel.getCredit_score());
        zhimaCreditService.authCallBack(Long.parseLong(callBackModel.getUser_id()), JSON.toJSONString(creditDataModel));
        return "ok";
    }

}
